from django import forms
from django.shortcuts import render, redirect, HttpResponse
from django.core.validators import RegexValidator
from django.core.exceptions import ValidationError

from mysite import models
from mysite.utills.pagenation import Pagination
from mysite.utills.bootstrap import BootStrapModelForm


def depart_list(request):
    """部门列表"""
    # # 1、获取到数据库里的所有数据
    # for i in range(50):
    #     models.Department.objects.create(title='数据中台')
    queryset = models.Department.objects.all()
    page_object = Pagination(request, queryset, page_size=10)

    context = {
        "queryset": page_object.page_queryset,
        "page_string": page_object.html()
    }
    return render(request, 'depart_list.html', context)


def depart_add(request):
    """添加部门"""
    if request.method == 'GET':
        return render(request, 'depart_add.html')
    # 获取用户提交的数据
    title = request.POST.get('title')
    # 保存到数据库
    models.Department.objects.create(title=title)
    # 重定向回到部门列表
    return redirect('/depart/list')

def depart_delete(request, nid):
    """删除部门"""
    # 1、获取ID
    # nid = request.GET.get('nid')
    # 2、删除ID
    models.Department.objects.filter(id=nid).delete()
    # 3、跳回部门列表
    return redirect('/depart/list')


def depart_edit (request, nid):
    """编辑部门"""
    # 这个’GET‘千万别小写，找了半天的错
    if request.method == 'GET':
        # 传入nid
        row_object = models.Department.objects.filter(id=nid).first()
        """修改部门"""
        return render(request, 'depart_edit.html', {'row_object': row_object})

    # 获取用户提交的title
    title = request.POST.get('title')
    # 根据ID找到数据库中的数据并更新
    models.Department.objects.filter(id=nid).update(title=title)
    # 回部门列表页面
    return redirect('/depart/list/')